package cn.jbolt.ec.commodity;

import cn.jbolt.base.JBoltBaseService;
import cn.jbolt.common.config.MainConfig;
import cn.jbolt.common.config.Msg;
import cn.jbolt.common.model.*;
import cn.jbolt.ec.cloud.QnService;
import cn.jbolt.ec.util.MyUtil;
import cn.jbolt.ec.wx.GenService;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Inject;
import com.jfinal.core.JFinal;
import com.jfinal.kit.Kv;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.upload.UploadFile;


import java.util.List;

/**
 * @author xieguo
 * @description 商品业务逻辑层
 * 引入option的操作
 */
public class CommodityService extends JBoltBaseService<BecRetailerCommodity> {

    @Inject
    CommodityOptionService optionService;

    @Inject
    CommodityTypeService commodityTypeService;

    @Inject
    CommodityFileService commodityFileService;

    @Override
    protected BecRetailerCommodity dao() {
        return new BecRetailerCommodity().dao();
    }



    /**
     * 通过类型筛选商品
     * @param type_id
     * @param pageNumber
     * @param pageSize
     * @return
     */
    public Page<BecRetailerCommodity> get_by_type(int type_id, int retailer_id,int pageNumber, int pageSize){
        Kv cond=Kv.by("type_id=",type_id).set("special_status=",0).set("retailer_id=",retailer_id).set("onsale_status=",1).set("is_del=",0).set("stock>",0);
        return paginate("id,name,price,bestseller,image",cond,pageNumber,pageSize,true);
    }

    /**
     * 查询商家特价商品信息
     * @param retailer_id
     * @param pageNumber
     * @param pageSize
     * @return
     */
    public Page<BecRetailerCommodity> special_commodity_info(
            Integer retailer_id,Integer pageNumber,Integer pageSize){
        Kv param=Kv.by("retailer_id",retailer_id).set("special_status",1);
        return paginate("*",param,pageNumber,pageSize,false);
    }

    /**
     * 查询订单商品信息
     * @param orderId
     * @return
     */
    public List<Record> order_commodity_info(String orderId){
        Kv param=Kv.by("orderId",orderId);
        return dbTemplate("ec.mall.shop.commodity.order_commodity_info",param).find();
    }

    /**
     *通过retailer_id，name搜索商品
     * @param retailer_id
     * @param pattern
     * @return
     */
    public Page<Record> search_by_retailer_id_and_name(Integer retailer_id,Integer special_status,String pattern,Integer pageNumber,Integer pageSize){
        Kv param=Kv.by("retailer_id",retailer_id).set("special_status",special_status).set("pattern",pattern);
        return dbTemplate("ec.mall.shop.commodity.search_by_retailer_id_and_name",param).paginate(pageNumber,pageSize);
    }

    /**
     * 商品详细信息
     * @param id
     * @return
     */
    public List<BecRetailerCommodity> commodity_details(Integer id){
        Kv param =Kv.by("id=",id).set("is_del=",0).set("stock>",0);
        return getCommonList("name,price,unit,special_status,special_price,special_stock,image,stock,content",param,true);
    }

    /**
     * 通过retailer_id获取商品类型
     * @param retailer_id
     * @return
     */
    public List<Record> get_commodity_type_by_retailer_id(Integer retailer_id){
        Kv param=Kv.by("retailer_id",retailer_id);
        return dbTemplate("ec.mall.shop.commodity.commodity_type_name",param).find();
    }

    /**
     * 通过retailer_id拿快速下单商品信息
     * @param retailer_id
     */
    public List<Record> quick_order_commodities(Integer retailer_id){
        Kv param=Kv.by("retailer_id",retailer_id);
        return dbTemplate("ec.mall.shop.commodity.quick_order_commodities",param).find();
    }


    /***************************************
     * 后台方法
     * @author  zedomi
     * ***********************************
     */


    /**
     * 后台管理分页查询
     * @param pageNumber
     * @param pageSize
     * @param keywords
     * @param onSale
     * @return
     */
    public Page<BecRetailerCommodity> paginateAdminData(int pageNumber, int pageSize, String keywords,
                                                        Integer onSale, Boolean isDelete, Integer commodityTypeId,
                                                        Integer retailer_id,Integer commodity_type_top_id,String status) {

        Kv paras=Kv.by("table",table());
        paras.setIfNotBlank("keywords",keywords);
        paras.setIfNotNull("onSale",onSale);
        paras.setIfNotNull("isDelete",isDelete);
        paras.setIfNotNull("retailer_id",retailer_id);
        paras.setIfNotNull("commodityTypeId",commodityTypeId);
        paras.setIfNotNull("commodity_type_top_id",commodity_type_top_id);
        paras.setIfNotNull("status",status);
        return dao().paginate(pageNumber, pageSize, Db.getSqlPara("ec.mall.manage.commodity.paginateAdminList", paras));

    }




    /**
     * 获取一个商品 并带着option表数据 属性 规格等信息
     * @param CommodityId
     * @return
     */
    public BecRetailerCommodity get_commodity_with_option(Integer CommodityId){
        BecRetailerCommodity becRetailerCommodity=findById(CommodityId);

        return becRetailerCommodity;
    }

    /**
     * 在进入添加页面时主动创建一个空商品
     * @param userId
     * @param CommodityTypeId
     * @return
     */
    public Ret create_commodity(Integer userId, Integer CommodityTypeId) {
        if(notOk(CommodityTypeId)){
            return fail(Msg.FAIL_NEED_CATEGORY);
        }
        BecRetailerCommodityType becRetailerCommodityType=commodityTypeService.findById(CommodityTypeId);
        if(becRetailerCommodityType==null){
            return fail(Msg.FAIL_NEED_CATEGORY);
        }

        BecRetailerCommodity becRetailerCommodity=new BecRetailerCommodity();


        becRetailerCommodity.setTypeId(CommodityTypeId);
        becRetailerCommodity.setBestseller(1);
        becRetailerCommodity.setLimitation(0);
        becRetailerCommodity.setOnsaleStatus(2);
        becRetailerCommodity.setPrice(new Long(10000));
        becRetailerCommodity.setImage("1");
        becRetailerCommodity.setSpecialStatus(0);
        becRetailerCommodity.setStock(1);
        becRetailerCommodity.setDiscount(-1);
        becRetailerCommodity.setName("新商品");
        becRetailerCommodity.setTopTypeId(MyUtil.me.get_top_commodity_type(CommodityTypeId));
        becRetailerCommodity.setContent("");



        boolean success=becRetailerCommodity.save();
        if(success){
            becRetailerCommodity.setName("新商品_"+becRetailerCommodity.getId());
            success=becRetailerCommodity.update();
            if(success){
                return success(becRetailerCommodity.getId(),Msg.SUCCESS);
            }
        }
        return FAIL;
    }

    /**
     * 切换上下架
     * @param userId
     * @param CommodityId
//     * @return
     */
    public Ret toggle_on_sale(Integer userId, Integer CommodityId) {

        BecRetailerCommodity becRetailerCommodity=findById(CommodityId);

        if(becRetailerCommodity.getIsDel()!=null&&becRetailerCommodity.getIsDel()==true){
            return fail("已经进入回收站的商品，不能切换此属性");
        }
        if (becRetailerCommodity.getOnsaleStatus()==1){
            becRetailerCommodity.setOnsaleStatus(2).update();
            return SUCCESS;
        }
        if (becRetailerCommodity.getOnsaleStatus()==2)
        {
            becRetailerCommodity.setOnsaleStatus(1).update();
            return SUCCESS;
        }

        return null;
    }

    /**
     * 对toggle_on_sale中的checkCanToggle进行覆盖
     * @param kv
     * @param becRetailerCommodity
     * @param column
     * @return
     */
    @Override
    public String checkCanToggle(Kv kv,BecRetailerCommodity becRetailerCommodity, String column) {
        if(becRetailerCommodity.getIsDel()!=null&&becRetailerCommodity.getIsDel()==true){
            return "已经进入回收站的商品，不能切换此属性";
        }

        return null;
    }
    /**
     * 更新商品 基本信息
     * @param userId
     * @param becRetailerCommodity
     * @return
     */
    public Ret update_commodity_base(Integer userId, BecRetailerCommodity becRetailerCommodity,String price,String special_price) {
        if(becRetailerCommodity==null||notOk(becRetailerCommodity.getId())||notOk(becRetailerCommodity.getName())){
            return fail(Msg.PARAM_ERROR);
        }
        if (special_price==null){
            Double double_commodity_price = Double.parseDouble(price)*100;
            Integer commodity_price=double_commodity_price.intValue() ;
            becRetailerCommodity.setPrice((long)commodity_price);
        }
        if (special_price!=null){
            Double double_commodity_price = Double.parseDouble(price)*100;
            Integer commodity_price=double_commodity_price.intValue() ;
            becRetailerCommodity.setPrice((long)commodity_price);

            Double double_commodity_price1 = Double.parseDouble(special_price)*100;
            Integer commodity_price1=double_commodity_price1.intValue() ;
            becRetailerCommodity.setSpecialPrice(commodity_price1);
        }

        return updateCommodityInfo(userId,becRetailerCommodity,"[基本信息]");
    }

    /**
     * 更新商品其他额外信息
     * @param userId
     * @param becRetailerCommodity
     * @param logAppend
     * @return
     */
    private Ret updateCommodityInfo(Integer userId, BecRetailerCommodity becRetailerCommodity, String logAppend) {
        if(becRetailerCommodity==null||notOk(becRetailerCommodity.getId())){
            return fail(Msg.PARAM_ERROR);
        }
        Ret ret=checkCanUpdate(becRetailerCommodity);
        if(ret.isFail()){
            return ret;
        }
        Integer changestock=0;
        BecRetailerCommodity b0  = new BecRetailerCommodity();
        BecRetailerCommodity becRetailerCommodity1  = b0.dao().findById(becRetailerCommodity.getId());
        BecRetailerStockChange becRetailerStockChange = new BecRetailerStockChange();
        if(becRetailerCommodity.getStock()!=null){
            changestock=becRetailerCommodity.getStock()-becRetailerCommodity1.getStock();
            if (changestock!=0){
                becRetailerStockChange.setAmount(changestock);
                becRetailerStockChange.setChangeType(2);
            }

        }
        if (becRetailerCommodity.getSpecialStock()!=null){
            changestock=becRetailerCommodity.getSpecialStock()-becRetailerCommodity1.getSpecialStock();
            becRetailerStockChange.setAmount(changestock);
            if (changestock>0){
                becRetailerStockChange.setChangeType(4);
            }
            if (changestock<0){
                becRetailerStockChange.setChangeType(5);
            }
        }

        becRetailerStockChange.setChangeTime(System.currentTimeMillis());
        becRetailerStockChange.setCommodityId(becRetailerCommodity.getId());

        becRetailerStockChange.setIsDel(false);
        becRetailerStockChange.setOperator(userId);
        if (changestock!=0){
            becRetailerStockChange.save();
        }

        boolean success=becRetailerCommodity.update();
        return ret(success);
    }

    /**
     * 检测是否可以修改
     * @param becRetailerCommodity
     * @return
     */
    private Ret checkCanUpdate(BecRetailerCommodity becRetailerCommodity) {
        if(becRetailerCommodity==null||notOk(becRetailerCommodity.getId())){
            return fail(Msg.PARAM_ERROR);
        }
        BecRetailerCommodity newBecCommodity=findById(becRetailerCommodity.getId());
        if(newBecCommodity==null){
            return fail(Msg.DATA_NOT_EXIST);
        }
        if(newBecCommodity.getOnsaleStatus()==1&&newBecCommodity.getIsDel()==false){
            return fail("已上架商品不能修改");
        }
        return SUCCESS;
    }

    /**
     * 更新商品的后台分类
     * @param userId
     * @param CommodityId
     * @param TypeId
     * @return
     */
    public Ret updateBackType(Integer userId, Integer CommodityId, Integer TypeId) {
        if(notOk(CommodityId)||notOk(TypeId)){return fail(Msg.PARAM_ERROR);}
        BecRetailerCommodityType becRetailerCommodityType=commodityTypeService.findById(TypeId);
        if(becRetailerCommodityType==null){
            return fail("所选分类的"+Msg.DATA_NOT_EXIST);
        }
        BecRetailerCommodity becRetailerCommodity=new BecRetailerCommodity().setId(CommodityId);
        Ret ret=checkCanUpdate(becRetailerCommodity);
        if(ret.isFail()){
            return ret;
        }
        becRetailerCommodity.setTypeId(TypeId);
        becRetailerCommodity.setTopTypeId(MyUtil.me.get_top_commodity_type(TypeId));
        boolean success=becRetailerCommodity.update();
        return ret(success);
    }

    /**
     * 更新商品图文详情(富文本框使用！！！！！！！！！！！)
     * @param becRetailerCommodity
     * @return
     */
    public Ret update_text_commodity(BecRetailerCommodity becRetailerCommodity) {
        BecApp becApp= GenService.getApp();
        if(becRetailerCommodity==null||notOk(becRetailerCommodity.getId())){
            return fail(Msg.PARAM_ERROR);
        }
        String contents=becRetailerCommodity.getContent();
        String contentss[]=contents.split("\"");
        int   k=contentss.length;
        int i=0;
        int q;
        while(true){

            q=contentss[i].indexOf("upload");
            if (q!=-1){

                String key1=becApp.getOtherCfgStr8()+contentss[i];

                System.out.println(key1);
                String key2=QnService.upload(key1);
                contentss[i]=key2;
            }


            if (i==(k-1)) break;
            i++;

        }
        String best="";
        for (int l=0;l<contentss.length;l++){

            best=best+contentss[l];
            if (l!=contentss.length-1)
                best=best+"\"";
        }

        becRetailerCommodity.setContent(best);
        if (becRetailerCommodity!=null){
            Boolean success= becRetailerCommodity.update();
            if (success){
                return success("更新成功");
            }
            else return fail("更新失败");
        }
        else return fail("更新失败");
    }


    /**
     * 检测是否可以修改
     * @param becRetailerCommodity
     * @return
     */
    public Ret check_can_edit_commodity(BecRetailerCommodity becRetailerCommodity) {
        if(becRetailerCommodity.getIsDel()){return fail("已删除商品，不能修改商品后端分类");}
        if(becRetailerCommodity.getOnsaleStatus()==1){return fail("已上架商品，不能修改商品后端分类");}
        return SUCCESS;
    }


    /**
     * 软删除商品
     * @param CommodityId
     * @return
     */
    public Ret delete_commodity(Integer userId, Integer CommodityId) {
        if(MainConfig.DEMO_MODE) {return fail(Msg.DEMO_MODE_CAN_NOT_DELETE);}
        if(notOk(CommodityId)){return fail(Msg.PARAM_ERROR);}
        BecRetailerCommodity becRetailerCommodity=findById(CommodityId);
        if(becRetailerCommodity==null){return fail(Msg.DATA_NOT_EXIST);}
        if(becRetailerCommodity.getOnsaleStatus()==1){return fail("商品已上架，不能删除;下架此商品后可以删除。");}

        becRetailerCommodity.setIsDel(true);
        boolean success=becRetailerCommodity.update();
        return ret(success);
    }
    /**
     * 恢复回收站内的商品
     * @param userId
     * @param CommodityId
     * @return
     */
    public Ret restore_commodity(Integer userId, Integer CommodityId) {
        if(notOk(CommodityId)){return fail(Msg.PARAM_ERROR);}
        BecRetailerCommodity becRetailerCommodity=findById(CommodityId);
        if(becRetailerCommodity==null){return fail(Msg.DATA_NOT_EXIST);}
        becRetailerCommodity.setIsDel(false);
        boolean success=becRetailerCommodity.update();
        return ret(success);
    }

    /**
     * 得到回收站内商品数量
     * @return
     */
    public int getDeleteCount() {
        return getCount(Kv.by("is_del", true));
    }

    /**
     * 更新商品图片信息
     * @param userId
     * @param becRetailerCommodity
     * @return
     */
    public Ret updateImages(Integer userId, BecRetailerCommodity becRetailerCommodity) {

        if(becRetailerCommodity==null||notOk(becRetailerCommodity.getId())){
            return fail(Msg.PARAM_ERROR);
        }
        Boolean success=becRetailerCommodity.update();
        if (success)
        {
            return success("上传成功");
        }
        else {
            return fail("上传失败");
        }

    }
    /**
     * 保存content图片
     */
    public Ret save_content_image(String key,UploadFile file, String uploadPath){
        String localUrl= JFinal.me().getConstants().getBaseUploadPath()+uploadPath+"/"+file.getFileName();

        return success(localUrl,"上传成功");
    }



    /**
     * 秒杀商品 添加时  二级选项数据源
     * 选择商品
     * @param retailer_id
     * @return
     */
    public List<BecRetailerCommodity> rush_commodity_select_comodity(Integer retailer_id){
        return getCommonList("id,name",Kv.by("retailer_id",retailer_id));

    }

}
